const express = require('express');
const router = express.Router();
const { User, Course } = require('../../models')
const { Op } = require('sequelize')
const {success, failure } = require('../../utils/responses');
const{NotFoundError}=require('../../utils/errors')

//查询用户列表
router.get('/', async function (req, res) {
    try {
        const query = req.query
        // 当前页数，如果不传值默认第一页
        const currentPage = Math.abs(Number(query.currentPage)) || 1
        // 每页显示的数量，如果不传值默认10
        const pageSize = Math.abs(Number(query.pageSize)) || 10
        //计算offset
        const offset = (currentPage - 1) * pageSize

        const condition = {
            order: [['id']],
            limit: pageSize,
            offset: offset
        }

        if (query.email) {
            condition.where = {
                email: {
                    [Op.eq]: query.email
                }
            }
        }
        if (query.username) {
            condition.where = {
                username: {
                    [Op.eq]: query.username
                }
            }
        }
        if (query.nickname) {
            condition.where = {
                nickname: {
                    [Op.like]: `%${query.nickname}%`
                }
            }
        }
        if (query.role) {
            condition.where = {
                role: {
                    [Op.eq]: query.role
                }
            }
        }
        const { count, rows } = await User.findAndCountAll(condition)
        success(res, '用户查询成功', {
            users: rows,
            pagination: {
                total: count,
                currentPage,
                pageSize
            }
        })
    } catch (error) {
        failure(res, error)
    }

})
//查询用户详情
router.get('/:id', async function (req, res) {
    try {
        const user = await getUser(req)
        success(res, '查询用户成功', { user })

    } catch (error) {
        failure(res, error)
    }

})

//创建用户
router.post('/', async function (req, res) {
    try {
        //创建白名单过滤
        const body = filterBody(req)
        const user = await User.create(body);
        //200和201都表示成功,201表示创建新的资源
        success(res, '创建用户成功', { user }, 201)
    } catch (error) {
        failure(res, error)
    }
})

//删除用户
router.delete('/:id', async function (req, res) {
    try {
        // const delUser = 1
        const user = await getUser(req)
        // const count = await Course.count({ where: { userId: req.params.id } })

        // if (count > 0) {
        //     return res.json({
        //         message: `该用户已有${count}个课程，确定注销吗`
        //     })
        // } else {
        //     await user.destroy()
        //     success(res, '删除用户成功')
        // }
        await user.destroy()
        success(res, '删除用户成功')

    } catch (error) {
        failure(res, error)
    }
})

//更新用户
router.put('/:id', async function (req, res) {
    try {
        const user = await getUser(req)

        //创建白名单过滤
        const body = filterBody(req)

        //更新用户
        await user.update(body)
        success(res, '更新用户成功', { user })

    } catch (error) {
        failure(res, error)
    }
})

//查询当前用户：公共方法
async function getUser(req) {
    //获取用户ID
    const { id } = req.params
    //查询当前用户ID
    const user = await User.findByPk(id)

    //如果用户不存在，抛出错误异常
    if (!user) {
        throw new NotFoundError(`ID:${id}用户不存在`)
    }
    return user
}

// 白名单过滤：公共方法
function filterBody(req) {
    return {
        email: req.body.email,
        username: req.body.username,
        password: req.body.password,
        nickname: req.body.nickname,
        sex: req.body.sex,
        avatar: req.body.avatar,
        company: req.body.company,
        introduce: req.body.introduce,
        role: req.body.role,
    }
}
module.exports = router;